package com.wnxy.sdd.front.config;

import com.google.common.hash.BloomFilter;
import com.wnxy.sdd.front.mapper.CourseMapper;
import com.wnxy.sdd.front.vo.IndexCourseQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class IndexCache implements CommandLineRunner {
    @Autowired
    private BloomFilter<String> bloomFilter;//引入布隆过滤器
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public void run(String... args) throws Exception {
        String cacheKey = "newCourse:4";
        //判断布隆过滤器中是否拥有这个Key
        if(!bloomFilter.mightContain(cacheKey)){
            bloomFilter.put(cacheKey);//将键添加到布隆过滤器中
        }
        // 尝试从Redis缓存中获取数据
        List cachedResult = redisTemplate.opsForList().range(cacheKey, 0, -1);
        System.out.println("cachedResult = " + cachedResult);
        if (cachedResult == null || cachedResult.size() == 0) {

            // 缓存未命中，查询数据库
            List<IndexCourseQueryVo> result = courseMapper.queryNewCourse(4);
            // 将结果存入Redis缓存
            for (IndexCourseQueryVo vo : result) {
                redisTemplate.opsForList().rightPush(cacheKey,vo);
            }
        }
    }
}